import {
  ModelOptions
} from '@/dva/types';

import { State } from './types';

import * as effects from './effects';

const initState: State = {
  pagination: {
    page: 1,
    limit: 20,
    total: 0
  },
  list: [],
  loading: false,
  submitLoading: false
};

const findFn = (id: string) => ({ _id }: any) => id === _id;

export default {
  namespace: 'imageClassify',
  state: initState,
  reducers: {
    setState(state, { payload }) {
      return { ...state, ...payload };
    },
    setList(state, { payload }) {
      const { list, pagination, push = false } = payload;
      const newList = push ? [...state.list, ...list] : list;
      const newState = { ...state, list: newList };
      if (pagination) newState.pagination = pagination;
      return newState;
    },
    updateItem(state, { payload }) {
      const { list = [] } = state;
      const { id, ...rest } = payload;
      const index = list.findIndex(findFn(id));
      if (index > -1) {
        const item = list[index];
        list[index] = { ...item, ...rest };
        state.list = [...list];
      }
      return state;
    },
    deleteItem(state, { payload }) {
      const { list } = state;
      const { id } = payload;
      const index = list.findIndex(findFn(id));
      if (index > -1) {
        list.splice(index, 1);
        state.list = [...list];
      }
      return state;
    }
  },
  effects: effects,
} as ModelOptions<State>;
